define([
    'dojo/_base/declare',
    'dojo/_base/array',
    'esri/Color',
    'dojo/_base/connect',
    'esri/SpatialReference',
    'esri/geometry/Point',
    'esri/graphic',
    'esri/symbols/SimpleMarkerSymbol',
    'esri/symbols/TextSymbol',
    'esri/dijit/PopupTemplate',
    'geomap/plugins/layers/ExGraphicsLayer',
], function (
    declare,
    arrayUtils,
    Color,
    connect,
    SpatialReference,
    Point,
    Graphic,
    SimpleMarkerSymbol,
    TextSymbol,
    PopupTemplate,
    ExGraphicsLayer
) {
    return declare([ExGraphicsLayer], {
        constructor: function (options) {
            this._clusterTolerance = options.distance || 50;
            //  this._clusterData = options.data || [];
            this._clusters = [];
            this._clusterLabelColor = options.labelColor || '#000';

            this._clusterLabelOffset = options.hasOwnProperty('labelOffset')
                ? options.labelOffset
                : -5;

            this._singles = [];
            this._showSingles = options.hasOwnProperty('showSingles') ? options.showSingles : true;
            // symbol for single graphics
            var SMS = SimpleMarkerSymbol;
            this._symbol = options.symbol || new SMS('circle', 10, null, new Color([0, 0, 200]));
            this._singleTemplate =
                options.singleTemplate || new PopupTemplate({ title: '', description: '{*}' });
            this._maxSingles = options.maxSingles || 1000;

            this._webmap = options.hasOwnProperty('webmap') ? options.webmap : false;

            this._sr = options.spatialReference || new SpatialReference({ wkid: 4326 });

            this._zoomEnd = null;
            this._onClickEvent = options.onClickEvent;
            this._rendererSingleField = options.rendererSingleField;
            this._renderSingleEvt = options.renderSingleEvt;
            this._renderSingleCallback = options.renderSingleCallback;
            this._xField = options.xField || 'x';
            this._yField = options.yField || 'y';
        },
        // override esri/layers/GraphicsLayer methods
        _setMap: function (map, surface) {
            // calculate and set the initial resolution
            this._clusterResolution = map.extent.getWidth() / map.width; // probably a bad default...

            // connect to onZoomEnd so data is re-clustered when zoom level changes
            this._zoomEnd = connect.connect(map, 'onZoomEnd', this, function () {
                // update resolution
                this._clusterResolution = this._map.extent.getWidth() / this._map.width;
                this.clear();
                this._setAddGraphics();
            });

            // GraphicsLayer will add its own listener here
            var div = this.inherited(arguments);
            return div;
        },

        _unsetMap: function () {
            this.inherited(arguments);
            connect.disconnect(this._zoomEnd);
        },

        // public ClusterLayer methods
        add: function (p) {
            // Summary:  The argument is a data point to be added to an existing cluster. If the data point falls within an existing cluster, it is added to that cluster and the cluster's label is updated. If the new point does not fall within an existing cluster, a new cluster is created.
            //
            // if passed a graphic, use the GraphicsLayer's add method
            if (p.declaredClass) {
                this.inherited(arguments);
                return;
            }

            // add the new data to _clusterData so that it's included in clusters
            // when the map level changes
            this._clusterData.push(p);
            var clustered = false;
            // look for an existing cluster for the new point
            for (var i = 0; i < this._clusters.length; i++) {
                var c = this._clusters[i];
                if (this._clusterTest(p, c)) {
                    // add the point to an existing cluster
                    this._clusterAddPoint(p, c);
                    // update the cluster's geometry
                    this._updateClusterGeometry(c);
                    clustered = true;
                    break;
                }
            }

            if (!clustered) {
                this._clusterCreate(p);
                p.clusterCount = 1;
                this._showCluster(p);
            }
        },
        clear: function () {
            // Summary:  Remove all clusters and data points.
            this.inherited(arguments);
            this._clusters.length = 0;
        },

        clearSingles: function (singles) {
            // Summary:  Remove graphics that represent individual data points.
            var s = singles || this._singles;
            arrayUtils.forEach(
                s,
                function (g) {
                    this.remove(g);
                },
                this
            );
            this._singles.length = 0;
        },

        onClick: function (e) {
            if ($.isFunction(this._onClickEvent)) {
                this._onClickEvent(e);
            }
        },
        _setAddGraphics: function () {
            var map = this._map;
            if (!map) {
                return;
            }
            var scale = map.getScale();
            var level = map.getLevel();
            if (!this._clusterData || this._clusterData.length < 1) {
                return;
            }
            var length = this._clusterData.length;

            if (
                this._thresholdValue >= length ||
                scale <= this._clusterUpperLimitScale ||
                (this._clusterUpperLimitLevel && level >= this._clusterUpperLimitLevel)
            ) {
                this._clusters = [...this._clusterData];
                this._showAllClusters();
            } else {
                this._clusterGraphics();
            }
        },
        // internal methods
        _clusterGraphics: function () {
            if (this._clusterData.length < 1) {
                return;
            }

            // first time through, loop through the points
            for (var j = 0, jl = this._clusterData.length; j < jl; j++) {
                // see if the current feature should be added to a cluster
                var point = this._clusterData[j];
                var clustered = false;
                var numClusters = this._clusters.length;
                for (var i = 0; i < this._clusters.length; i++) {
                    var c = this._clusters[i];
                    if (this._clusterTest(point, c)) {
                        this._clusterAddPoint(point, c);
                        clustered = true;
                        break;
                    }
                }

                if (!clustered) {
                    this._clusterCreate(point);
                }
            }
            this._showAllClusters();
        },

        _clusterTest: function (p, cluster) {
            var distance =
                Math.sqrt(
                    Math.pow(cluster.x - p[this._xField], 2) +
                        Math.pow(cluster.y - p[this._yField], 2)
                ) / this._clusterResolution;
            return distance <= this._clusterTolerance;
        },

        // points passed to clusterAddPoint should be included
        // in an existing cluster
        // also give the point an attribute called clusterId
        // that corresponds to its cluster
        _clusterAddPoint: function (p, cluster) {
            // average in the new point to the cluster geometry
            var count, x, y;
            p.x = p[this._xField];
            p.y = p[this._yField];

            // build an extent that includes all points in a cluster
            // extents are for debug/testing only...not used by the layer
            if (p.x < cluster.extent[0]) {
                cluster.extent[0] = p.x;
            } else if (p.x > cluster.extent[2]) {
                cluster.extent[2] = p.x;
            }
            if (p.y < cluster.extent[1]) {
                cluster.extent[1] = p.y;
            } else if (p.y > cluster.extent[3]) {
                cluster.extent[3] = p.y;
            }
        },

        // point passed to clusterCreate isn't within the
        // clustering distance specified for the layer so
        // create a new cluster for it
        _clusterCreate: function (p) {
            var clusterId = this._clusters.length + 1;

            p.clusterId = clusterId;
            p.extent = [p[this._xField], p[this._yField], p[this._xField], p[this._yField]];
            // create the cluster
            var cluster = Object.assign(p);
            this._clusters.push(cluster);
        },

        _showAllClusters: function () {
            for (var i = 0, il = this._clusters.length; i < il; i++) {
                var c = this._clusters[i];
                this._showCluster(c);
            }
        },

        _showCluster: function (c) {
            var me = this;
            if (!c.x || !c.y) {
                return;
            }
            var point = new Point(c.x, c.y, this._sr);
            var symbolFieldName = me.options.symbolFieldName || me._mapView.getSymbolFieldName();
            if (c[symbolFieldName]) {
                me.__getSymbol(me._mapView, c[symbolFieldName], function (symbol) {
                    me.add(new Graphic(point, symbol, c));
                });
            } else if (this._symbol) {
                this.add(new Graphic(point, this._symbol, c));
            }
        },
        _updateClusterGeometry: function (c) {
            // find the cluster graphic
            var cg = arrayUtils.filter(this.graphics, function (g) {
                return !g.symbol && g.clusterId == c.clusterId;
            });
            if (cg.length == 1) {
                cg[0].geometry.update(c.x, c.y);
            } else {
                console.log("didn't find exactly one cluster geometry to update: ", cg);
            }
        },

        // debug only...never called by the layer
        _clusterMeta: function () {
            // print total number of features
            console.log('Total:  ', this._clusterData.length);

            // add up counts and print it
            var count = 0;
            arrayUtils.forEach(this._clusters, function (c) {
                count += c.clusterCount;
            });
            console.log('In clusters:  ', count);
        },
    });
});
